package org.example.travel.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.travel.common.RedisKeyUtil;
import org.example.travel.common.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.Duration;

@Slf4j
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 获取 token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            return true; // 没有 token，不拦截，让 LoginInterceptor 再处理
        }

        // 2. 获取 Redis 中的 userId
        String key = RedisKeyUtil.tokenKey(token);
        String userIdStr = redisTemplate.opsForValue().get(key);
        if (userIdStr == null) {
            return true; // token 无效或过期，也不拦截
        }

        // 3. 保存到 ThreadLocal
        UserHolder.setUserId(Long.parseLong(userIdStr));

        // 4. 刷新 token 过期时间
        redisTemplate.expire(key, Duration.ofMinutes(30));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.remove(); // 防止内存泄漏
    }
}
